package com.zhiwen.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiwen.common.exception.BusinessException;
import com.zhiwen.domain.dto.ShareDTO;
import com.zhiwen.domain.entity.Answer;
import com.zhiwen.domain.entity.Question;
import com.zhiwen.domain.entity.ShareRecord;
import com.zhiwen.mapper.ShareRecordMapper;
import com.zhiwen.service.AnswerService;
import com.zhiwen.service.QuestionService;
import com.zhiwen.service.ShareService;
import com.zhiwen.domain.vo.ShareVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 分享服务实现类
 */
@Service
@RequiredArgsConstructor
public class ShareServiceImpl extends ServiceImpl<ShareRecordMapper, ShareRecord> implements ShareService {

    private final QuestionService questionService;
    private final AnswerService answerService;

    @Value("${application.base-url:http://localhost:8080}")
    private String baseUrl;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShareVO createShare(ShareDTO shareDTO, HttpServletRequest request) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();

        // 检查目标对象是否存在
        ShareVO shareVO = checkAndPrepareShare(shareDTO);

        // 记录分享操作
        ShareRecord shareRecord = new ShareRecord();
        shareRecord.setUserId(userId);
        shareRecord.setTargetType(shareDTO.getTargetType());
        shareRecord.setTargetId(shareDTO.getTargetId());
        shareRecord.setPlatform(shareDTO.getPlatform());
        shareRecord.setCreateTime(LocalDateTime.now());
        shareRecord.setIpAddress(getIpAddress(request));
        shareRecord.setDeleted(0);

        this.save(shareRecord);

        // 设置分享记录ID
        shareVO.setId(shareRecord.getId());

        return shareVO;
    }

    @Override
    public ShareVO getShareDetail(Long id) {
        // 获取分享记录
        ShareRecord shareRecord = this.getById(id);
        if (shareRecord == null) {
            throw new BusinessException("分享记录不存在");
        }

        // 通过分享记录获取分享详情
        ShareDTO shareDTO = new ShareDTO();
        shareDTO.setTargetType(shareRecord.getTargetType());
        shareDTO.setTargetId(shareRecord.getTargetId());

        return checkAndPrepareShare(shareDTO);
    }

    @Override
    public String generateShareLink(ShareDTO shareDTO) {
        // 生成唯一标识符
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 构建分享链接
        String shareLink = baseUrl + "/share/";

        if (shareDTO.getTargetType() == 1) {
            // 问题分享
            shareLink += "question/" + shareDTO.getTargetId() + "?share=" + uuid;
        } else if (shareDTO.getTargetType() == 2) {
            // 回答分享
            shareLink += "answer/" + shareDTO.getTargetId() + "?share=" + uuid;
        }

        return shareLink;
    }

    /**
     * 检查并准备分享信息
     *
     * @param shareDTO 分享DTO
     * @return 分享VO
     */
    private ShareVO checkAndPrepareShare(ShareDTO shareDTO) {
        ShareVO shareVO = new ShareVO();

        if (shareDTO.getTargetType() == 1) {
            // 问题
            Question question = questionService.getById(shareDTO.getTargetId());
            if (question == null) {
                throw new BusinessException("问题不存在");
            }

            shareVO.setTitle(question.getTitle());
            shareVO.setDescription(question.getContent().length() > 100
                    ? question.getContent().substring(0, 100) + "..."
                    : question.getContent());
            shareVO.setShareUrl(baseUrl + "/question/" + question.getId());
            // 这里使用默认图片，实际应用中可以根据问题配图或系统默认图设置
            shareVO.setImageUrl(baseUrl + "/static/images/share-default.png");

        } else if (shareDTO.getTargetType() == 2) {
            // 回答
            Answer answer = answerService.getById(shareDTO.getTargetId());
            if (answer == null) {
                throw new BusinessException("回答不存在");
            }

            Question question = questionService.getById(answer.getQuestionId());

            shareVO.setTitle("回答：" + question.getTitle());
            shareVO.setDescription(answer.getContent().length() > 100
                    ? answer.getContent().substring(0, 100) + "..."
                    : answer.getContent());
            shareVO.setShareUrl(baseUrl + "/question/" + question.getId() + "/answer/" + answer.getId());
            // 使用默认图片
            shareVO.setImageUrl(baseUrl + "/static/images/share-default.png");

        } else {
            throw new BusinessException("无效的分享类型");
        }

        return shareVO;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request HTTP请求
     * @return IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
